/*
 * FileName: AskThread.java
 * Author:   zzw
 * Date:     2018年05月26日
 * Description:
 */
package com.zzw.concurrency;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class AskThread implements Runnable {

    private CompletableFuture<Integer> re = null;

    public AskThread(CompletableFuture<Integer> re) {
        this.re = re;
    }

    @Override
    public void run() {
        int myRe = 0;
        try {
            myRe = re.get() * re.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println(myRe);
    }

    public static Integer calc(Integer para){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //int r = para / 0;
        return para * para;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /*CompletableFuture<Integer> future = new CompletableFuture<>();
        new Thread(new AskThread(future)).start();
        Thread.sleep(2000);
        future.complete(60);*/

       /* CompletableFuture<Void> future = CompletableFuture
                .supplyAsync(() -> calc(50))
                .exceptionally(ex -> {
                    System.out.println(ex.toString());
                    return 0;
                })
                .thenApply((i) -> Integer.toString(i))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        future.get();*/

      /*  CompletableFuture<Void> future = CompletableFuture
                .supplyAsync( ()-> calc(50))
                .thenCompose((i) -> CompletableFuture.supplyAsync(()->calc(i)))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        try {
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }*/

        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync( ()-> calc(50));
        CompletableFuture<Integer> future2 = CompletableFuture
                .supplyAsync( ()-> calc(50));

        CompletableFuture<Void> fu = future.thenCombine(future2, (x, y) -> (x + y))
                .thenApply((str) -> "\"" + str + "\"")
                .thenAccept(System.out::println);
        fu.get();
    }

    @Test
    public void test1(){

    }
}
